package edu.yuhf.service;

import java.util.List;

import edu.yuhf.dao.iface.PermissionDao;
import edu.yuhf.dao.iface.PermissionRoleDao;
import edu.yuhf.dao.mysql.PermissionJdbcDaoImpl;
import edu.yuhf.dao.mysql.PermissionRoleJdbcDaoImpl;
import edu.yuhf.domain.Page;
import edu.yuhf.domain.Permission;
import edu.yuhf.service.iface.PermissionService;

public class PermissionServiceImpl implements PermissionService{

	private PermissionDao permissionDao=new PermissionJdbcDaoImpl();
	private PermissionRoleDao permissionRoleDao=new PermissionRoleJdbcDaoImpl();
	
	@Override
	public void getPermission(Page<List<Permission>> page) {
		permissionDao.queryPermissions(page);
		 int totalRowNumber=permissionDao.queryTotalRowNumber(page);
		 int totalPageNumber=0==totalRowNumber%page.getPageNumber()?totalRowNumber/page.getPageNumber():totalRowNumber/page.getPageNumber()+1;
		 page.setTotalRowNumber(totalRowNumber);
		 page.setTotalPageNumber(totalPageNumber);
		
	}

	@Override
	public boolean addPermission(Permission permission) {
		boolean flag=false;
		if(1==permissionDao.insertPermission(permission)) {
			flag=true;
		}
		return flag;
	}

	@Override
	public boolean removePermission(String ids) {
		boolean flag=false;
		if(permissionDao.deletePermissions(ids)!=0) {
			flag=true;
		}
		return flag;
	}

	@Override
	public Permission getPermissionById(int id) {
		return permissionDao.queryPermissionById(id);
	}

	@Override
	public boolean setPermission(Permission permission) {
		boolean flag=false;
		if(permissionDao.updatePermission(permission)==1) {
			flag=true;
		}
		return flag;
	}

	@Override
	public List<Permission> getParentPermission() {
		return permissionDao.queryParentPermissions();
	}

	@Override
	public List<Permission> getAllPermission(int roleId) {
		List<Permission> rolePermissions=permissionRoleDao.queryPermissionsByRoleId(roleId);
		List<Permission> list=permissionDao.queryAllPermission();
		list.forEach(element->{
			rolePermissions.forEach(permission->{
				if(element.getId()==permission.getId()) {
					element.setChecked(true);
				}
			});
		});
		return list;
	}

	@Override
	public List<Permission> getPermissionByUserId(int id) {
		List<Permission> list=permissionDao.queryPermissionByUserId(id);
		List<Permission> parentList=permissionDao.queryParentPermissions();
		parentList.forEach(parentPermission->{
			if(!list.contains(parentPermission)){
				for(Permission p:list){
					if(p.getPid()==parentPermission.getId()){
						list.add(parentPermission);
						break;
					}
				}
			}
		});
		return list;
	}

}
